/*
 * Copyright (c) 2012 Shanda Corporation. All rights reserved.
 *
 * Created on 2012-8-17.
 */

package com.whq.knowverywell.activity;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import android.content.Intent;
import android.graphics.drawable.ColorDrawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.PopupWindow.OnDismissListener;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;
import android.widget.TextView;
import android.widget.Toast;

import com.whq.knowverywell.R;
import com.whq.knowverywell.business.LoginUtil;
import com.whq.knowverywell.business.db.TblUserHandler;
import com.whq.knowverywell.business.http.LoginRequestUtil;
import com.whq.knowverywell.business.model.BaseJsonResponse;
import com.whq.knowverywell.business.model.User;
import com.whq.knowverywell.util.LogUtil;
import com.whq.knowverywell.util.StringUtil;
import com.whq.knowverywell.util.TipUtil;
import com.whq.knowverywell.util.constant.ErrorCodeConstant;
import com.whq.knowverywell.util.constant.ModelConstant;

/**
 * 登录后的acivity基类.
 *
 * @author wanghuaiqiang
 */
public class BaseLoginActivity extends BaseActivity {
    private final static String TAG = "BaseLoginActivity";

    public static final int MENU_ITEM_ID_LOGOUT = 10;
    public static final int MENU_ITEM_ID_MANAGER_ACCOUNT = 20;
    public static final int MENU_ITEM_ID_ABOUT = 30;
    
    private static final int SORT_TYPE_ASC 				= 0;
    private static final int SORT_TYPE_DESC 			= 1;
    private static final String SORT_ITEM_NAME 			= "name";
    private static final String SORT_ITEM_SALE_COUNT 	= "sale_count";
    private static final String SORT_ITEM_SALE_AMOUNT 	= "sale_amount";
    private static final Map<String, Integer> MAP_SORT_ITEM_TYPE_DESC_OR_ASC = new HashMap<String, Integer>(0);
    static {
    	MAP_SORT_ITEM_TYPE_DESC_OR_ASC.put(SORT_ITEM_NAME, 			SORT_TYPE_DESC);
    	MAP_SORT_ITEM_TYPE_DESC_OR_ASC.put(SORT_ITEM_SALE_COUNT, 	SORT_TYPE_DESC);
    	MAP_SORT_ITEM_TYPE_DESC_OR_ASC.put(SORT_ITEM_SALE_AMOUNT, 	SORT_TYPE_DESC);
    }

    protected TextView mSelectedTextView, mSumTextView, mAmountTextView, mLoginNameTextView;
    protected ImageView mHiddenSortImageView, mHiddenRefreshImageView, mHiddenManagerImageView;
    protected PopupWindow mSortPopupWindow, mManagerPopupWindow;
    protected LinearLayout mAccountChangeLinearLayout = null;

    private ImageView dscOfCityImageView;
    private ImageView ascOfCityImageView;
    private ImageView dscOfSaleAmountImageView;
    private ImageView ascOfSaleAmountImageView;
    private ImageView dscOfSaleCountImageView;
    private ImageView ascOfSaleCountImageView;

    protected String[] itemTitles = new String[]{"汇总统计", "地域分析", "品类分析", "货品查询", "热销查询"};
    protected int itemId;
    protected int durationType;
    protected int fragmentType;
    protected String productNo;
    protected String fragmentTitle;
    protected OnSortListener mListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        LogUtil.d(TAG, "onCreate start ...");
        super.onCreate(savedInstanceState);
        getParameters();
        initManagerPopupWindow();

        // set manager popup window data
        final String loginName = LoginUtil.getLoginUserName(this);
        mLoginNameTextView.setText(loginName);

    }

    @Override
    protected void onResume() {
        super.onResume();

        if (!LoginUtil.chkLogin(this)) {
            Toast.makeText(BaseLoginActivity.this, "您已经退出登录或者在其他设备上登录！", Toast.LENGTH_SHORT).show();

            Intent intent = new Intent(this, LoginActivity.class);
            startActivity(intent);
            this.finish();
            return;
        }
        
        // add account to account change linearlayout
        this.addAccounts2Menu();
    }

    // --------- customize method ---------
    
    /**
     * 把登录过的所有账号添加到菜单上
     */
    private void addAccounts2Menu() {
    	if (mAccountChangeLinearLayout == null) {
    		return ;
    	}
    	
    	mAccountChangeLinearLayout.removeAllViews();
    	
    	TblUserHandler tblUserHandler = new TblUserHandler(this);
    	
    	List<User> userList = tblUserHandler.getAllUsers();
    	if ( (userList == null) || (userList.isEmpty()) ) {
    		return ;
    	}
    	
    	for (Iterator<User> iterator = userList.iterator(); iterator.hasNext();) {
			User oneUser = (User) iterator.next();
			if (oneUser == null) {
				continue;
			}
			
			final String groupCode = oneUser.getGroupCode();
			final String userName = oneUser.getUserName();
			final String password = oneUser.getPassword();
			
			TextView account = new TextView(this);
	        LinearLayout.LayoutParams llps = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, 60);
	        llps.gravity = Gravity.CENTER_HORIZONTAL;
	        llps.setMargins(15, 0, 0, 0);
	        account.setLayoutParams(llps);
	        account.setText(oneUser.getUserName());
	        account.setOnClickListener(new OnClickListener() {
	            @Override
	            public void onClick(View v) {
	            	doChgAccount(groupCode, userName, password);
	            }
	        });
	        mAccountChangeLinearLayout.addView(account);
		}
    }
    
    /**
     * 参数获取
     */
    protected void getParameters() {

    }

    /**
     * 刷新按钮按下
     */
    protected void doRefresh() {

    }

    /**
     * 跳转到账号管理页面
     */
    protected void go2ManagerAccount() {
        Intent intent = new Intent(BaseLoginActivity.this, ManagerAccountActivity.class);
        startActivity(intent);
    }
    
    /**
     * 跳转到关于页面
     */
    protected void go2AboutActivity() {
        Intent intent = new Intent(BaseLoginActivity.this, AboutActivity.class);
        startActivity(intent);
    }

    /**
     * 初始化排序菜单
     */
    protected void initSortPopupWindow() {
        View menuView = getLayoutInflater().inflate(R.layout.sort_popup_window, null);
        RelativeLayout cityLayout = (RelativeLayout) menuView.findViewById(R.id.city);
        TextView sortNameOfCityTextView = (TextView) cityLayout.findViewById(R.id.sort_name_textview);
        sortNameOfCityTextView.setText("名称");
        dscOfCityImageView = (ImageView) cityLayout.findViewById(R.id.sort_dsc_imageview);
        ascOfCityImageView = (ImageView) cityLayout.findViewById(R.id.sort_asc_imageview);
        
        
        RelativeLayout saleAmountLayout = (RelativeLayout) menuView.findViewById(R.id.sale_amount);
        TextView sortNameOfSaleAmountTextView = (TextView) saleAmountLayout.findViewById(R.id.sort_name_textview);
        sortNameOfSaleAmountTextView.setText("销售额");
        dscOfSaleAmountImageView = (ImageView) saleAmountLayout.findViewById(R.id.sort_dsc_imageview);
        ascOfSaleAmountImageView = (ImageView) saleAmountLayout.findViewById(R.id.sort_asc_imageview);
        
        RelativeLayout saleCountLayout = (RelativeLayout) menuView.findViewById(R.id.sale_count);
        TextView sortNameOfSaleCountTextView = (TextView) saleCountLayout.findViewById(R.id.sort_name_textview);
        sortNameOfSaleCountTextView.setText("销量");
        dscOfSaleCountImageView = (ImageView) saleCountLayout.findViewById(R.id.sort_dsc_imageview);
        ascOfSaleCountImageView = (ImageView) saleCountLayout.findViewById(R.id.sort_asc_imageview);
        
        dscOfCityImageView.setVisibility(View.GONE);
        ascOfCityImageView.setVisibility(View.GONE);
        dscOfSaleAmountImageView.setVisibility(View.GONE);
        ascOfSaleAmountImageView.setVisibility(View.GONE);
        dscOfSaleCountImageView.setVisibility(View.GONE);
        ascOfSaleCountImageView.setVisibility(View.GONE);
        
        cityLayout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	dscOfCityImageView.setVisibility(View.GONE);
            	ascOfCityImageView.setVisibility(View.GONE);
            	dscOfSaleAmountImageView.setVisibility(View.GONE);
            	ascOfSaleAmountImageView.setVisibility(View.GONE);
            	dscOfSaleCountImageView.setVisibility(View.GONE);
            	ascOfSaleCountImageView.setVisibility(View.GONE);
            	
            	int orderByNameType = MAP_SORT_ITEM_TYPE_DESC_OR_ASC.get(SORT_ITEM_NAME);
            	orderByNameType = (orderByNameType == SORT_TYPE_ASC) ? SORT_TYPE_DESC : SORT_TYPE_ASC;
            	MAP_SORT_ITEM_TYPE_DESC_OR_ASC.put(SORT_ITEM_NAME, orderByNameType);
            	
            	if (orderByNameType == SORT_TYPE_ASC) {
            		ascOfCityImageView.setVisibility(View.VISIBLE);
            	} else {
            		dscOfCityImageView.setVisibility(View.VISIBLE);
            	}
            	
            	String sortStr = (orderByNameType == SORT_TYPE_ASC) ? ModelConstant.ORDER_BY_NAME_ASC : ModelConstant.ORDER_BY_NAME_DESC ;
            	mListener.doSortInPopupWindow(sortStr);
            }
        });
        
        saleAmountLayout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	dscOfCityImageView.setVisibility(View.GONE);
            	ascOfCityImageView.setVisibility(View.GONE);
            	dscOfSaleAmountImageView.setVisibility(View.GONE);
            	ascOfSaleAmountImageView.setVisibility(View.GONE);
            	dscOfSaleCountImageView.setVisibility(View.GONE);
            	ascOfSaleCountImageView.setVisibility(View.GONE);
            	
            	int orderBySaleAmountType = MAP_SORT_ITEM_TYPE_DESC_OR_ASC.get(SORT_ITEM_SALE_AMOUNT);
            	orderBySaleAmountType = (orderBySaleAmountType == SORT_TYPE_ASC) ? SORT_TYPE_DESC : SORT_TYPE_ASC;
            	MAP_SORT_ITEM_TYPE_DESC_OR_ASC.put(SORT_ITEM_SALE_AMOUNT, orderBySaleAmountType);
            	
            	if (orderBySaleAmountType == SORT_TYPE_ASC) {
            		ascOfSaleAmountImageView.setVisibility(View.VISIBLE);
            	} else {
            		dscOfSaleAmountImageView.setVisibility(View.VISIBLE);
            	}
            	
            	String sortStr = (orderBySaleAmountType == SORT_TYPE_ASC) ? ModelConstant.ORDER_BY_SALES_AMOUNT_ASC : ModelConstant.ORDER_BY_SALES_AMOUNT_DESC ;
            	mListener.doSortInPopupWindow(sortStr);
            }
        });
        
        saleCountLayout.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
            	dscOfCityImageView.setVisibility(View.GONE);
            	ascOfCityImageView.setVisibility(View.GONE);
            	dscOfSaleAmountImageView.setVisibility(View.GONE);
            	ascOfSaleAmountImageView.setVisibility(View.GONE);
            	dscOfSaleCountImageView.setVisibility(View.GONE);
            	ascOfSaleCountImageView.setVisibility(View.GONE);
            	
            	int orderBySaleCountType = MAP_SORT_ITEM_TYPE_DESC_OR_ASC.get(SORT_ITEM_SALE_COUNT);
            	orderBySaleCountType = (orderBySaleCountType == SORT_TYPE_ASC) ? SORT_TYPE_DESC : SORT_TYPE_ASC;
            	MAP_SORT_ITEM_TYPE_DESC_OR_ASC.put(SORT_ITEM_SALE_COUNT, orderBySaleCountType);
            	
            	if (orderBySaleCountType == SORT_TYPE_ASC) {
            		ascOfSaleCountImageView.setVisibility(View.VISIBLE);
            	} else {
            		dscOfSaleCountImageView.setVisibility(View.VISIBLE);
            	}
            	
            	String sortStr = (orderBySaleCountType == SORT_TYPE_ASC) ? ModelConstant.ORDER_BY_SALES_VOLUME_ASC : ModelConstant.ORDER_BY_SALES_VOLUME_DESC ;
            	mListener.doSortInPopupWindow(sortStr);
            }
        });
        
        
//        dscOfCityImageView.setOnClickListener(new OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
//                dscOfCityImageView.setSelected(true);
//                ascOfCityImageView.setSelected(false);
//
//                dscOfSaleAmountImageView.setSelected(false);
//                ascOfSaleAmountImageView.setSelected(false);
//
//                dscOfSaleCountImageView.setSelected(false);
//                ascOfSaleCountImageView.setSelected(false);
//
//                mListener.doSortInPopupWindow(ModelConstant.ORDER_BY_NAME_DESC);
//                // TipUtil.tipDescription(BaseLoginActivity.this, "城市 降序");
//            }
//        });
//
//        ascOfCityImageView.setOnClickListener(new OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
//                dscOfCityImageView.setSelected(false);
//                ascOfCityImageView.setSelected(true);
//
//                dscOfSaleAmountImageView.setSelected(false);
//                ascOfSaleAmountImageView.setSelected(false);
//
//                dscOfSaleCountImageView.setSelected(false);
//                ascOfSaleCountImageView.setSelected(false);
//
//                mListener.doSortInPopupWindow(ModelConstant.ORDER_BY_NAME_ASC);
//                // TipUtil.tipDescription(BaseLoginActivity.this, "城市 升序");
//            }
//        });
//
//        
//        dscOfSaleAmountImageView.setOnClickListener(new OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
//                dscOfSaleAmountImageView.setSelected(true);
//                ascOfSaleAmountImageView.setSelected(false);
//
//                dscOfCityImageView.setSelected(false);
//                ascOfCityImageView.setSelected(false);
//
//                dscOfSaleCountImageView.setSelected(false);
//                ascOfSaleCountImageView.setSelected(false);
//
//                mListener.doSortInPopupWindow(ModelConstant.ORDER_BY_SALES_AMOUNT_DESC);
//                // TipUtil.tipDescription(BaseLoginActivity.this, "销售额 降序");
//            }
//        });
//
//        ascOfSaleAmountImageView.setOnClickListener(new OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
//                dscOfSaleAmountImageView.setSelected(false);
//                ascOfSaleAmountImageView.setSelected(true);
//
//                dscOfCityImageView.setSelected(false);
//                ascOfCityImageView.setSelected(false);
//
//                dscOfSaleCountImageView.setSelected(false);
//                ascOfSaleCountImageView.setSelected(false);
//
//                mListener.doSortInPopupWindow(ModelConstant.ORDER_BY_SALES_AMOUNT_ASC);
//                // TipUtil.tipDescription(BaseLoginActivity.this, "销售额 升序");
//            }
//        });
//
//        
//        dscOfSaleCountImageView.setOnClickListener(new OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
//                dscOfSaleCountImageView.setSelected(true);
//                ascOfSaleCountImageView.setSelected(false);
//
//                dscOfCityImageView.setSelected(false);
//                ascOfCityImageView.setSelected(false);
//
//                dscOfSaleAmountImageView.setSelected(false);
//                ascOfSaleAmountImageView.setSelected(false);
//
//                mListener.doSortInPopupWindow(ModelConstant.ORDER_BY_SALES_VOLUME_DESC);
//                // TipUtil.tipDescription(BaseLoginActivity.this, "销量 降序");
//            }
//        });
//
//        ascOfSaleCountImageView.setOnClickListener(new OnClickListener() {
//
//            @Override
//            public void onClick(View v) {
//                dscOfSaleCountImageView.setSelected(false);
//                ascOfSaleCountImageView.setSelected(true);
//
//                dscOfCityImageView.setSelected(false);
//                ascOfCityImageView.setSelected(false);
//
//                dscOfSaleAmountImageView.setSelected(false);
//                ascOfSaleAmountImageView.setSelected(false);
//
//                mListener.doSortInPopupWindow(ModelConstant.ORDER_BY_SALES_VOLUME_ASC);
//                // TipUtil.tipDescription(BaseLoginActivity.this, "销量 升序");
//            }
//        });

        mSortPopupWindow = new PopupWindow(menuView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        ColorDrawable cd = new ColorDrawable(-0000);
        mSortPopupWindow.setBackgroundDrawable(cd);
        mSortPopupWindow.setOutsideTouchable(true);
        mSortPopupWindow.setFocusable(true);
        mSortPopupWindow.setTouchable(true);
        mSortPopupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                LogUtil.d(TAG, "mPopupWindow touch action : " + event.getAction() + " view id : " + v.getId());

                if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                    LogUtil.d(TAG, "mPopupWindow outside touch .");
                    mSortPopupWindow.dismiss();
                    return true;
                }
                return false;
            }

        });
        mSortPopupWindow.setOnDismissListener(new OnDismissListener() {

            @Override
            public void onDismiss() {
                // mSortPopupWindow.setVisibility(View.GONE);
            }
        });
        // mSortPopupWindow.setAnimationStyle(R.style.popupWindow);
    }

    /**
     * 初始化管理菜单
     */
    protected void initManagerPopupWindow() {
        View menuView = getLayoutInflater().inflate(R.layout.manager_popup_window, null);
        mLoginNameTextView = (TextView) menuView.findViewById(R.id.login_name_textview);
        mAccountChangeLinearLayout = (LinearLayout) menuView.findViewById(R.id.account_linearlayout);
        RelativeLayout logoutRelativeLayout = (RelativeLayout) menuView.findViewById(R.id.logout_relativelayout);
        logoutRelativeLayout.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                BaseLoginActivity.this.logout();
            }
        });
        TextView manageAccountTextView = (TextView) menuView.findViewById(R.id.manage_account_textview);
        manageAccountTextView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                BaseLoginActivity.this.go2ManagerAccount();
            }
        });
        TextView abountTextView = (TextView) menuView.findViewById(R.id.about_textview);
        abountTextView.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
            	BaseLoginActivity.this.go2AboutActivity();
            }
        });

        mManagerPopupWindow = new PopupWindow(menuView, LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        ColorDrawable cd = new ColorDrawable(-0000);
        mManagerPopupWindow.setBackgroundDrawable(cd);
        mManagerPopupWindow.setOutsideTouchable(true);
        mManagerPopupWindow.setFocusable(true);
        mManagerPopupWindow.setTouchable(true);
        mManagerPopupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                LogUtil.d(TAG, "mPopupWindow touch action : " + event.getAction() + " view id : " + v.getId());

                if (event.getAction() == MotionEvent.ACTION_OUTSIDE) {
                    LogUtil.d(TAG, "mPopupWindow outside touch .");
                    mManagerPopupWindow.dismiss();
                    return true;
                }
                return false;
            }

        });
        mManagerPopupWindow.setOnDismissListener(new OnDismissListener() {

            @Override
            public void onDismiss() {
                // mManagerPopupWindow.setVisibility(View.GONE);
            }
        });
        // mManagerPopupWindow.setAnimationStyle(R.style.popupWindow);
    }

    public interface OnSortListener {
        public void doSortInPopupWindow(String orderBy);
    }
    
    private void doChgAccount(String groupCode, String userName, String password) {
    	// 如果切换到当前登录帐号
    	if ( (groupCode != null) 
				&& (userName != null) 
				&& (groupCode.equals(LoginUtil.getLoginGroupCode(BaseLoginActivity.this)))
				&& (userName.equals(LoginUtil.getLoginUserName(BaseLoginActivity.this)))
				) {
			TipUtil.tipDescription(BaseLoginActivity.this, "无法切换到当前登录帐号！");
		} else {
			new ChgAccountTask(groupCode, userName, password).execute();
		}
    }
    
    private void handleChgAccountResult(BaseJsonResponse loginResponse) {
		if ( (loginResponse == null) 
				|| (loginResponse.getResultCode() != ErrorCodeConstant.ERR_CODE_SUCCESS) 
				) {
			String resultMsg = loginResponse.getResultMsg();
			if (StringUtil.isBlank(resultMsg)) {
				resultMsg = "登录失败！";
			}
			TipUtil.tipDescription(this, resultMsg);
			Intent intent = new Intent(this, LoginActivity.class);
			startActivity(intent);
			this.finish();
		} else {
			TipUtil.tipDescription(this, "登录成功！");
			Intent intent = new Intent(this, HomeActivity.class);
			startActivity(intent);
			this.finish();
		} 
	}
	
	class ChgAccountTask extends AsyncTask<String, String, String> {
		private BaseJsonResponse loginResponse = new BaseJsonResponse();
		
		private String groupCode = "";
		private String userName = "";
		private String password = "";
		
		public ChgAccountTask(String groupCode, String userName, String password) {
			this.groupCode = groupCode;
			this.userName = userName;
			this.password = password;
		}
		
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			openProgressDialog("正在切换账号");
		}
		
		@Override
		public String doInBackground(String... params) {
			this.loginResponse = LoginRequestUtil.login(BaseLoginActivity.this, this.groupCode, this.userName, this.password, true);
			return null;
		}
		
		@Override
		public void onPostExecute(String result) {
			closeProgressDialog();
			handleChgAccountResult(this.loginResponse);
		}
	}
}
